//实现qsort(冒泡排序版)
#include <stdio.h>
#include <string.h>

struct Stu
{
    char name[20];
    int age;
};

int cmp_stu_by_name(const void* e1, const void* e2)
{
    return strcmp(((struct Stu*)e1)->name, ((struct Stu*)e2)->name);//从第一个字符开始比，比较ascll码值
}

int cmp_stu_by_age(const void* e1, const void* e2)
{
    return ((struct Stu*)e1)->age - ((struct Stu*)e2)->age;
}

void Swap(char* buf1, char* buf2, int width)
{
    int k = width;
    while(k--)
    {
        char tmp = *(buf1 + k);
        *(buf1 + k) = *(buf2 + k);
        *(buf2 + k) = tmp;
    }
}

void my_qsort(void* base, int num, int width, int(* cmp)(const void* e1, const void* e2))
{
    int flag = 1;
    for(int i = 0; i < num - 1; i++)
    {
        for(int j = 1; j < num - i; j++)
        {
            if(cmp(((char*)base + width*(j - 1)), ((char*)base + width*j)) > 0)//传入待比较的两个元素的地址
            {
                //交换
                Swap(((char*)base + width*(j - 1)), ((char*)base + width*j), width);
                flag = 0;
            }
        }
        if(flag == 1)
        {
            break;
        }
    }
}

void test2()//排结构体
{
    struct Stu s[] = {{"zhangsan", 15}, {"lisi", 30}, {"wangwu", 25}};
    int sz = sizeof(s) / sizeof(s[0]);
    my_qsort(s, sz, sizeof(s[0]), cmp_stu_by_name);
    
    int i = 0;
    for(i = 0; i < 3; i++)
    {
        printf("%s ", s[i].name);
    }

    printf("\n");

    my_qsort(s, sz, sizeof(s[0]), cmp_stu_by_age);
    
    for(i = 0; i < 3; i++)
    {
        printf("%d ", s[i].age);
    }
}

int main()
{
    test2();
    return 0;
}